using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web.UI;

namespace OpenWaves.Web.Controls
{
    public class HierarchicalEnumerableToNavigationNodeAdapter : INavigationNode
    {
        public static IEnumerable<INavigationNode> From(IHierarchicalEnumerable hierarchicalEnumerable)
        {
            Contract.Requires<ArgumentNullException>(hierarchicalEnumerable != null);
            Contract.Ensures(Contract.Result<IEnumerable<INavigationNode>>() != null);
            foreach (var item in hierarchicalEnumerable)
            {
                var hierarchyData1 = hierarchicalEnumerable.GetHierarchyData(item);
                yield return new HierarchicalEnumerableToNavigationNodeAdapter(hierarchyData1, (INavigateUIData)hierarchyData1);
            }
        }


        private IEnumerable<INavigationNode> children;
        public IEnumerable<INavigationNode> Children
        {
            get
            {
                if (this.children == null)
                    this.children = From(this.hierarchyData.GetChildren()).ToList();
                return this.children;
            }
        }

        public Url Url
        {
            get { return Url.Parse(this.navigateUIData.NavigateUrl); }
        }

        public string Name
        {
            get { return this.navigateUIData.Name; }
        }

        public string Description
        {
            get { return this.navigateUIData.Description; }
        }

        public bool IsVisibleInMenu
        {
            get { return true; }
        }

        private readonly IHierarchyData hierarchyData;
        private readonly INavigateUIData navigateUIData;

        private HierarchicalEnumerableToNavigationNodeAdapter(IHierarchyData hierarchyData, INavigateUIData navigateUIData)
        {
            this.hierarchyData = hierarchyData;
            this.navigateUIData = navigateUIData;
        }
    }
}